package com.yqg.protection.netty;

import com.yqg.protection.netty.handler.ProtocolData;
import com.yqg.protection.netty.handler.ProtocolHandler;
import com.yqg.protection.netty.handler.factory.ProtocolHandlerFactory;
import com.yqg.protection.utils.DataSaver;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@ChannelHandler.Sharable
@Log4j2
public class MainProtocolHandler extends SimpleChannelInboundHandler<String> {

    @Autowired
    private ProtocolHandlerFactory handlerFactory;
    @Autowired
    private DataSaver dataSaver;
    @Resource(name = "dataExecutor")
    private ThreadPoolTaskExecutor executor;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String data) throws Exception {
        String saveTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        dataSaver.saveDataToFileAsync(data, saveTime, "原始数据");

        // 解析协议头
        String header = getHeader(data);
        log.info("收到协议: {}", header);

        // 获取对应处理器
        ProtocolHandler handler = handlerFactory.getHandler(header);
        if (handler == null) {
            log.warn("不支持的协议头: {}", header);
            return;
        }

        // 封装协议数据
        ProtocolData protocolData = new ProtocolData();
        protocolData.setRawData(data);
        protocolData.setHeader(header);
        protocolData.setSaveTime(saveTime);
        protocolData.setCtx(ctx);
        protocolData.setExecutor(executor);
        protocolData.setDataSaver(dataSaver);

        // 生成并发送响应
        byte[] response = handler.generateResponse(protocolData);
        ctx.writeAndFlush(response);

        // 处理业务逻辑
        handler.handle(protocolData);
    }

    // 修改getHeader方法，确保FE协议正确处理
    private String getHeader(String data) {
        if (data == null || data.isEmpty()) {
            return "";
        }

        // FE协议的特殊处理
        if (data.startsWith("fd")) {
            return "FD";
        } else if (data.startsWith("fe")) {
            return "FE";
        } else if (data.startsWith("4040")) {
            return "4040";
        } else if (data.startsWith("5d6c")) {
            return "5d6c";
        }

        return data.length() >= 2 ? data.substring(0, 2) : data;
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端断开连接");
        // 原有断开连接逻辑
    }
}
